<?php

namespace app\api\controller\v35;

use app\api\controller\v13\Auth2;
use app\common\cachemodel\AppConfig;
use app\common\cachemodel\AppUserDeviceRecord;
use app\common\cachemodel\Fortune;
use app\common\cachemodel\FortuneNote;
use app\common\cachemodel\IndexButton;
use app\common\cachemodel\lucky\AppLuckyTaskRecord;
use app\common\cachemodel\ZlUserVip;
use app\common\lib\ConfigManage;
use app\common\lib\exception\ApiException;
use app\common\lib\Util;
use app\common\model\AppNotice;
use app\common\model\Recode as RecodeModel;
use app\common\model\Slide;
use app\common\model\UserPush;
use app\zyhsapi\model\ZyhsConsultChatRecord;
use Exception;
use think\Cache;
use think\Env;
use think\Log;

/**
 * @title 首页接口
 * @desc 首页改版
 * @version 2.9.0
 * Class Index
 * @package app\api\controller\v33
 */
class Index extends Auth2
{
    protected $restActionList = ['index'];

    protected $userDeviceId = '';

    protected $weekDay = [
        0 => '周日',
        1 => '周一',
        2 => '周二',
        3 => '周三',
        4 => '周四',
        5 => '周五',
        6 => '周六',
    ];

    /**
     * @title 首页接口
     * @method GET
     * @desc 无需另外传参
     * @readme /doc/api/index/index.md
     * @return \think\response\Json
     * @throws ApiException
     * @throws Exception
     */
    public function index()
    {
        $isYoung = $this->user ? $this->user['young_model'] : false; // 是否是青少年模式
        $contentType = input('content_type/d', 2) === 2 ? 2 : 1;
        $time_now = time();
        $in_sign = input('in_sign/d', 1);
        $timezone = $this->headers['timezone'] ?? 8;
        $uid = $this->user ? (int)$this->user['id'] : null;
        if ($this->user && $this->user['rid'])
        {  // 开启青少年模式时，禁止访问幸运星
            $luckyNeedAuth = $isYoung ? 3 : 2;
            $astroCalendarNeedAuth = $isYoung ? 3 : 0;

            $map = ['uid' => $this->user['id'], 'isself' => 1];
            $recode_info = (new RecodeModel())->getSelfRecode($map);

            if (!$recode_info || !$recode_info['sun'])
            {
                return show(406, '档案缺失请添加档案');
            }

            $in_sign = explode('-', $recode_info['sun'])[0];
        } else
        {
            // 未登录，已选择星座用户，展示今日天象信息
            $luckyNeedAuth = 2;
            $astroCalendarNeedAuth = 0;
            if (!in_array($in_sign, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], true))
            {
                return show(408, '请选择星座');
            }
        }

        // 首页按钮
        $btnsData = (new IndexButton())->getIndexButtonV2([
            'ver' => $this->headers['version'],
            'app_type' => $this->headers['app-type'],
            'userinfo' => $this->user,
        ], true, $isYoung, $this->is_apple_check);
        //安卓开启审核模式时且是华为渠道,不展示占卜
        if ($this->android_audit_mode_swtich && stripos($this->headers['channel'], 'huawei') !== false)
        {
            foreach ($btnsData['btn2'] as $key => $btn)
            {
                if ($btn['type'] === 'divination_question')
                {
                    $link = preg_replace('/^divination_question.*/', "divination_question?type=0&name1='占星骰子'&need_auth=0", $btn['link']);
                    $btnsData['btn2'][$key]['young_link'] = $btnsData['btn2'][$key]['link'] = $link;
                }
            }
        }
        if ($isYoung)
        {
            $articles = null;
            $slide = null;
        } else
        {
            // 首页轮播
            $slide = (new Slide())->getSlideVersion([]);
        }

        //获取运势相关数据
        $revive_day = null;
        $fortune_cache = [];
        //若登录则计算今日运势获取三星数据
        if ($this->user['rid'])
        {
            try
            {
                $dayFortuneVersion = 3;// 每日运势柱状图有调整
                $fortune_cache = (new Fortune())->fortuneDayHomeData($this->user['rid'], $time_now, $dayFortuneVersion);
                //将今日运势图片替换为新图标
                $new_icon = explode('/', $fortune_cache['revive_day']['icon_url']);
                if (Util::CheckAppVersion('2.9.0') === '同' || Util::CheckAppVersion('2.9.0') === '大')
                {
                    array_splice($new_icon, 5, 0, ['v4']);
                } else if (Util::CheckAppVersion('2.4.2') === '小')
                {
                    array_splice($new_icon, 5, 0, ['v2']);
                } else
                {
                    array_splice($new_icon, 5, 0, ['v3']);
                }
                $fortune_cache['revive_day']['icon_url'] = implode('/', $new_icon);
            }
            catch (\Exception $e)
            {
                // 错误信息写入日志
                Log::write('首页获取日运缓存数据错误:' . 'uid=[' . $this->user['id'] . ']' . $e->getMessage(), 'error');
                throw new ApiException('服务异常，请稍后再试~');
            }
            //若今日运势为3级
            if ((int)($fortune_cache['revive_day']['star_level'] ?? 0) === 3)
            {
                $revive_day = $fortune_cache['revive_day'];
                $fortune_cache = [];//目录配置里层获取今日运势是否计算开关控制，$fortune_cache为空，则里层需要计算
            }
        }

        $date = gmdateModify('Y-m-d', time(), 8, $timezone);
        $birth = [];
        if ($this->user)
        {
            $userPush = (new UserPush())->getUserRegid($this->user['id']);
            $calendarBirthdayStatus = (int)($userPush['calendar_birthday_status'] ?? 1);
            if ($calendarBirthdayStatus === 1)
            {
                //获取用户今日生日信息
                $recodeData = (new \app\common\cachemodel\Recode())->userBirthMonthList($this->user, $date, $timezone);
                $host = Env::get('host.domain');
                $newMonth = gmdateModify('n-j', time(), 8, (float)$timezone);//当前时区的当前时间
                foreach ($recodeData as $recodeDatum)
                {
                    $recodeMonth = (int)$recodeDatum['month'];
                    $recodeDay = (int)$recodeDatum['day'];
                    //获取自己今日生日的信息
                    if ($recodeDatum['type'] == 1 && $newMonth == $recodeMonth . '-' . $recodeDay)
                    {
                        $birth = [
                            'text' => $recodeDatum['text'],
                            'target' => 'link',
                            'link' => $host . $recodeDatum['link'],
                        ];
                        break;
                    }
                }
            }
        }
        //获取公告相关信息
        $AppNotice = new AppNotice();
        $notice = $AppNotice->getNewestNotice($birth, $uid);
        if ($notice && (!$isYoung || ($notice['young_model'] ?? false)))
        {   // 如果为开启青少年模式 或者 青少年模式下也显示
            $notice['content'] = $notice['des'];
            //公告为jpg或gif时算出向上偏移比例【算法：（图片居中时距上的高度 - 蓝狐所给距上的高度）/ 模板或手机的高度】保留两位
            if (in_array($notice['img_type'], [2, 3]))
            {
                $notice['img_top_height'] = -0.07;//图片距上高度比例 当img_type为2，3时存在，否则不存在,负数是向上偏移，正数是向下偏移
            }
            unset($notice['des'], $notice['young_model']);
        } else
        {
            $notice = null;
        }

        //获取首页目录配置信息
        $indexConfig = ConfigManage::indexCategoryV4($this->user, $in_sign, $this->headers['version'], $fortune_cache, $contentType);

        $luckyIsNew = $this->user ? (new AppLuckyTaskRecord())->getIndexIsNew($this->user['id']) : 0;

        $data = [
            'in_sign' => (int)$in_sign,
            'slides' => $slide,
            'buttons' => $btnsData['btn2'],
            'fortune_category' => $indexConfig['fortune_category'],
            'lucky_planet_switch' => true,// 幸运星功能开关
            'notice' => $notice,
            'is_young_model' => $isYoung ? 1 : 2,
            'lucky_need_auth' => $luckyNeedAuth,
            'today_revive_day' => $revive_day,
            'astro_calendar' => [
                'target' => 'local',
                'link' => 'astro_calendar?date=' . $date . '&need_auth=' . $astroCalendarNeedAuth . '&umeng_event_name=common_target_link&umeng_event_label=' . urlencode('星象日历-首页顶部导航栏-点击'),
            ],
            'astro_calendar_need_auth' => $astroCalendarNeedAuth,
            'week' => $this->weekDay[date('w')],
            'date' => date('m.d'),
            //  幸运星信息
            'lucky_info' => [
                'target' => 'local',
                'link' => 'lucky_star_home?need_auth=' . $luckyNeedAuth, //  青少年模式下 lucky_star_home?need_auth=3
                'is_new' => $luckyNeedAuth === 3 ? 0 : $luckyIsNew, // 当天未进行过签到或有幸运星待领取时，展示小红点
                'img' => 'https://oss.goddessxzns.com/test/lucky_star/lucky_start1.png',
            ],
            'recommend_btns' => $btnsData['btn1'],
            'year_fortune_new_icon_is_show' => 0,
        ];

        // 登录后才做任务  VIP 每日任务
        if ($this->user)
        {
            (new ZlUserVip())->updateStarNum((int)$this->user['id'], 9);
        }

        $data['has_bind_tel'] = (($this->user['tel'] ?? '') || ($this->user['temporary_tel'] ?? '')) ? 1 : 0;
        $data['live_info'] = [];
        //青少年模式不展示直播
        if ($isYoung === false)
        {
            $isLiveIng = $btnsData['is_live_ing'] ?? false; // 是否直播中
            $liveNative = 1;//1=>原生 0=>H5
            //获取直播预告信息
            $preview = $btnsData['preview_info'] ?? false;
            //若当前无公告框且预告直播间正在直播需要弹出公告框
            if (!$data['notice'] && $preview && $preview['notice_status'] && $isLiveIng === true)
            {
                $noticeInfo = json_decode($preview['extend'], true);
                if (!empty($noticeInfo['notice_info']))
                {
                    $data['notice'] = [
                        "id" => (int)('1000' . $preview['id']),
                        "type" => 1,//【1.弹一次； 2.每隔*天弹一次； 3.每次打开首页都弹一次； 4.每次都弹，不能关闭，没有关闭按钮（比如系统升级中等）；】
                        "sep_day" => 0, //每隔*天（当type=2时有效）
                        "img_url" => $noticeInfo['notice_info']['img_url'],
                        "img_width" => $noticeInfo['notice_info']['img_width'],
                        "img_height" => $noticeInfo['notice_info']['img_height'],
                        "img_type" => 1, //1=>默认白色背景的对话框 ，2=png/jpg(透明背景)，3=>gif（透明背景）
                        "img_top_height" => 0,//例如： -0.07，图片距上高度比例 当img_type为2，3时存在，否则不存在
                        "title" => $preview['broadcast_title'],
                        "content" => '',
                        "btn" => "点击进入直播间",
                        "target" => "local",
                        "link" => "live_web?live_id={$preview['live_id']}&live_record_id={$preview['record_id']}&live_native={$liveNative}&need_auth=0",
                    ];
                }
            }
        }

        $changeData = (new \app\common\cachemodel\zl2\AstroFortuneChange())->getIndexAstroFortuneChangeData($this->request->time(), $isYoung);

        $data['change_data'] = $changeData;
        $oss = Env::get('host.photo');
        //获取心情签到信息
        $data['mood_data'] = [
            'icon' => $oss . '/test/mood/happy_s.png',
            'name' => '心情',
            'target' => 'local',
            'link' => "mood_index?need_auth=2",
            'status' => 0,
        ];
        $appMoodNoteModel = new FortuneNote();
        $todayNoteInfo = $appMoodNoteModel->checkTodayNoteStatus($this->user['id']);
        if ($todayNoteInfo && !empty($todayNoteInfo['mood_icon_s']))
        {
            $data['mood_data']['icon'] = $todayNoteInfo['mood_icon_s'];
            $data['mood_data']['name'] = $todayNoteInfo['mood_name'];
            $data['mood_data']['status'] = 1;
        }

        $indexAdConfig = (new AppConfig())->configInfo('app');
        if (isset($indexAdConfig['index_ad_img']) && $indexAdConfig['index_ad_img'])
        {
            $data['ad_btn'] = [
                'img' => $indexAdConfig['index_ad_img'],
                'target' => $indexAdConfig['index_ad_target'] ?? '',
                'link' => isset($indexAdConfig['index_ad_link']) ? htmlspecialchars_decode($indexAdConfig['index_ad_link']) : '',
            ];
        }
        $chatConfig = (new AppConfig())->configInfo('chat_config');
        $data['ai_pop_switch'] = isset($chatConfig['ai_pop_switch']) && $chatConfig['ai_pop_switch'] ? 1 : 0;

        $deviceKey = 'user_device_id:' . md5($this->user['id'] . $this->headers['did']);
        /**
         * 绑定设备号,用于后台封禁设备
         */
        if ($this->headers['did'] && $this->user['id'] && !Cache::get($deviceKey))
        {
            $userDevice = (new AppUserDeviceRecord())->getUserDeviceInfo($this->user['id'], ['uid', 'device_id']);
            if (!$userDevice)
            {
                (new AppUserDeviceRecord())->saveData([
                    'status' => 1,
                    'device_id' => $this->headers['did'],
                    'uid' => $this->user['id'],
                    'create_time' => $this->request->time(),
                ]);
            } else
            {
                (new AppUserDeviceRecord())->updateData($this->headers['did'], $this->user['id']);
                Cache::set($deviceKey, 1, 86400);
            }
        }

        if ($this->user['id'] && Util::checkAppVersion('2.13.0') !== '小')
        {   //  服务 小红点------
            $consultChatRecordModel = new ZyhsConsultChatRecord();
            $newMsg = $consultChatRecordModel->getUserUnreadAllNum(2, $this->user['id']); // 未读消息数量
            $data['consult_tab_new_msg'] = $newMsg ? 1 : 0;
        }

        return show(200, '首页加载成功', $data);
    }
}
